package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.config.SparkAIConfig;
import com.sky.entity.ChatRecord;
import com.sky.mapper.ChatRecordMapper;
import com.sky.service.SparkAIService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class SparkAIServiceImpl implements SparkAIService {

    @Autowired
    private SparkAIConfig sparkAIConfig;

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    private final Map<String, List<RoleContent>> userHistoryMap = new ConcurrentHashMap<>();

    @Override
    public String chatWithAI(String userId, String question) {
        try {
            String url = sparkAIConfig.getUrl();
            String authHeader = "Bearer " + sparkAIConfig.getKey() + ":" + sparkAIConfig.getSecret();

            // 获取或创建用户历史记录
            List<RoleContent> historyList = userHistoryMap.computeIfAbsent(userId, k -> new ArrayList<>());

            // 使用fastjson构建请求JSON
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user", userId);
            jsonObject.put("model", sparkAIConfig.getModel());

            JSONArray messagesArray = new JSONArray();

            // 添加历史记录
            if (!historyList.isEmpty()) {
                for (RoleContent content : historyList) {
                    JSONObject message = new JSONObject();
                    message.put("role", content.role);
                    message.put("content", content.content);
                    messagesArray.add(message);
                }
            }

            // 添加当前问题
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", question);
            messagesArray.add(userMessage);

            // 保存用户问题到历史记录
            historyList.add(new RoleContent("user", question));

            jsonObject.put("messages", messagesArray);
            jsonObject.put("stream", false);
            jsonObject.put("max_tokens", sparkAIConfig.getMaxTokens());
            jsonObject.put("temperature", sparkAIConfig.getTemperature());

            // 发送请求
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", authHeader);
            con.setDoOutput(true);

            try (OutputStream os = con.getOutputStream()) {
                os.write(jsonObject.toString().getBytes("UTF-8"));
                os.flush();
            }

            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                // 读取错误响应
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                StringBuilder errorResponse = new StringBuilder();
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                log.error("Spark AI API returned error code: {}, response: {}", responseCode, errorResponse.toString());
                throw new RuntimeException("API request failed with code: " + responseCode + ", response: " + errorResponse.toString());
            }

            // 读取响应
            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }

            // 解析响应
            JSONObject responseJson = JSON.parseObject(response.toString());
            JSONArray choices = responseJson.getJSONArray("choices");
            if (choices == null || choices.isEmpty()) {
                log.error("Invalid response from Spark AI: {}", response.toString());
                throw new RuntimeException("Invalid response from AI service");
            }

            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            String aiResponse = message.getString("content");

            // 保存AI回复到历史记录
            historyList.add(new RoleContent("assistant", aiResponse));

            // 限制历史记录长度，防止内存溢出
            if (historyList.size() > 20) {
                historyList.subList(0, historyList.size() - 20).clear();
            }

            // 保存对话记录到数据库
            saveChatRecordToDatabase(userId, question, aiResponse);

            return aiResponse;

        } catch (Exception e) {
            log.error("Error calling Spark AI service", e);
            throw new RuntimeException("Failed to get response from AI service", e);
        }
    }

    /**
     * 保存对话记录到数据库
     * @param userId 用户ID
     * @param question 用户问题
     * @param aiResponse AI响应
     */
    private void saveChatRecordToDatabase(String userId, String question, String aiResponse) {
        try {
            // 将字符串userId转换为Long类型
            Long userIdLong = null;
            try {
                userIdLong = Long.parseLong(userId);
            } catch (NumberFormatException e) {
                log.warn("用户ID格式不正确，无法保存到数据库: {}", userId);
                return;
            }

            // 创建对话记录对象
            ChatRecord chatRecord = new ChatRecord();
            chatRecord.setUserId(userIdLong);
            chatRecord.setQuestion(question);
            chatRecord.setResponse(aiResponse);
            chatRecord.setCreateTime(LocalDateTime.now());
            chatRecord.setIsDeleted(0);

            // 保存到数据库
            chatRecordMapper.insert(chatRecord);
            log.info("成功保存用户{}的AI对话记录", userId);
        } catch (DataAccessException e) {
            // 捕获数据库异常并记录日志，但不中断主流程
            log.error("保存AI对话记录失败，用户ID: {}, 问题: {}", userId, question, e);
        } catch (Exception e) {
            log.error("保存AI对话记录时发生未知错误", e);
        }
    }

    @Override
    public void clearUserHistory(String userId) {
        userHistoryMap.remove(userId);
    }

    /**
     * 获取用户与AI的历史对话记录
     * @param userId 用户ID
     * @param page 页码
     * @param pageSize 每页记录数
     * @return 历史对话记录列表
     */
    @Override
    public List<ChatRecord> getChatHistory(Long userId, Integer page, Integer pageSize) {
        try {
            // 计算偏移量
            int offset = (page - 1) * pageSize;

            // 调用Mapper查询数据库
            return chatRecordMapper.selectByUserId(userId, offset, pageSize);
        } catch (Exception e) {
            log.error("查询用户{}历史记录失败", userId, e);
            throw new RuntimeException("查询历史记录失败", e);
        }
    }

    @Data
    @AllArgsConstructor
    static class RoleContent {
        String role;
        String content;
    }
}